﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.Calibration;
using Labthink.PCSoft.UniversalHost4.Model.DataManage;
using Labthink.PCSoft.UniversalHost4.Model.Flow;
using Labthink.PCSoft.UniversalHost4.Model.Query;
using Labthink.PCSoft.UniversalHost4.Model.Setting;
using Labthink.PCSoft.UniversalHost4.Model.TempCtrl;
using Labthink.PCSoft.UniversalHost4.Model.Unit;
using Labthink.PCSoft.UniversalHost4.Model.User;
using Newtonsoft.Json;
using NLog.Fluent;
using FullData = Labthink.PCSoft.UniversalHost4.Model.FullData;
using ParamScheme = Labthink.PCSoft.UniversalHost4.Model.ParamScheme;

namespace Labthink.PCSoft.UniversalHost4.TcpCommands
{
    public class Commands : ICommands
    {
        private DateTime _lastConnect;
        private Socket _socket;
        private byte[] _readBuffer;
        private bool _connected;
        private string _ip;
        private static string SplitStr = "\r\n\n\r";
        private SocketClient _query;
        private SocketClient _data;
        private string _seed;

        /// <summary>
        /// 查询连接
        /// </summary>
        [JsonIgnore]
        public SocketClient QueryConnection => _query;

        public bool IsConnected => _query.IsConnected;

        /// <summary>
        /// 数据连接,仅用于试验中的数据处理
        /// </summary>
        [JsonIgnore]
        public SocketClient DataConnection => _data;

        public event EventHandler<EventArgs> OnDisConnectHandler;
        public event EventHandler<DataArgs> OnReceiveRealtimeDataHandler;
        public event EventHandler<DataArgs> OnReceiveResultsDataHandler;
        public event EventHandler<DataArgs> OnReceiveParamDataHandler;
        public event EventHandler<TestInfoArgs> OnReceiveAllTestStartHandler;
        public event EventHandler<TestInfoArgs> OnReceiveAllTestStopHandler;
        public event EventHandler<TestInfoArgs> OnReceiveTestStartHandler;
        public event EventHandler<TestInfoArgs> OnReceiveTestStopHandler;
        public event EventHandler<StatusArgs> OnReceiveTestStatusHandler;
        public event EventHandler<AlarmArgs> OnReceiveTestAlarmHandler;
        public event EventHandler<CustomArgs> OnReceiveCustomHandler;
        public event EventHandler<BaseArgs> OnReceiveIsControlHandler;

        public Commands()
        {
        }
        public Commands(string ip)
        {
            InitCommand(ip);
        }

        #region 心跳处理

        /// <summary>
        /// 心跳, 客户端发送(2s一次), 服务器回应
        /// </summary>
        private void _sendHeart()
        {
            while (true)
            {
                if (_socket != null)
                {
                    try
                    {
                        var sd = new SocketData
                        {
                            ActionCode = "001",
                            Value = ""
                        };

                        var str = JsonConvert.SerializeObject(sd);
                        byte[] bytesArray = Encoding.UTF8.GetBytes(str + SplitStr);
                        _socket.Send(bytesArray);
                    }
                    catch (Exception e)
                    {
                        Log.Error().Exception(e).Write();
                        _connected = false;
                        _socket = null;
                        //抛出连接中断事件
                        OnDisConnectHandler?.Invoke(this, new EventArgs());
                    }
                }

                Thread.Sleep(2000);
            }
            // ReSharper disable once FunctionNeverReturns
        }

        private void _listenConnect()
        {
            while (true)
            {
                if (_connected)
                {
                    var ts = DateTime.Now - _lastConnect;
                    var wait = 10;
                    if (Debugger.IsAttached)
                    {
                        wait = 60 * 60 * 10;
                    }
                    if (ts.TotalSeconds > wait)
                    {
                        _connected = false;

                        //抛出连接中断事件
                        OnDisConnectHandler?.Invoke(this, new EventArgs());
                    }
                }

                Thread.Sleep(5000);
            }
            // ReSharper disable once FunctionNeverReturns
        }

        private void _receiveHeartBeat(IAsyncResult result)
        {
            try
            {
                if (result is null)
                {
                    return;
                }

                if (!(result.AsyncState is Socket c)) return;
                int length = c.EndReceive(result);
                if (length > 0)
                {
                    _lastConnect = DateTime.Now;
                    //var response = Encoding.UTF8.GetString(_readBuffer, 0, length);
                    //Log.Trace().Message($"heart beat {response}").Write();
                }

                c.BeginReceive(_readBuffer, 0, _readBuffer.Length, SocketFlags.None, _receiveHeartBeat, c);
            }
            catch (Exception ex)
            {
                Log.Error().Message(ex.Message).Write();
            }
        }
        #endregion

        /// <summary>
        /// 登录成功后再开启数据和心跳端口
        /// </summary>
        public void OpenConnection()
        {
            var r = _data.Connect();
            if (r)
            {
                _data.R2E = R2E;
                _data.ReceiveFromPort2();

            }
        }

        public void ReConnection()
        {
            _query.Connect();
        }

        public bool R2E(SocketData sd)
        {
            try
            {
                DataBar db;
                switch (sd.ActionCode)
                {
                    case "-03":
                        //异常
                        if (OnReceiveTestAlarmHandler == null) return false;
                        Log.Trace().Message("调用异常处理事件").Write();
                        OnReceiveTestAlarmHandler.Invoke(this, new AlarmArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Alarm = JsonConvert.DeserializeObject<AlarmPlus>(sd.Value) });
                        break;

                    case "111":
                        //单个试验开始
                        if (OnReceiveTestStartHandler == null) return false;
                        Log.Trace().Message("调用单个试验开始处理事件").Write();
                        OnReceiveTestStartHandler.Invoke(this, new TestInfoArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Info = JsonConvert.DeserializeObject<TestInfo>(sd.Value) });
                        break;

                    case "112":
                        //单个试验结束
                        if (OnReceiveTestStopHandler == null) return false;
                        Log.Trace().Message("调用单个试验结束处理事件");
                        OnReceiveTestStopHandler.Invoke(this, new TestInfoArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Info = JsonConvert.DeserializeObject<TestInfo>(sd.Value) });
                        break;

                    case "113":
                        //全部试验开始
                        if (OnReceiveAllTestStartHandler == null) return false;
                        Log.Trace().Message("调用试验全部开始处理事件").Write();
                        OnReceiveAllTestStartHandler.Invoke(this, new TestInfoArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Info = JsonConvert.DeserializeObject<TestInfo>(sd.Value) });
                        break;

                    case "114":
                        //全部试验结束
                        if (OnReceiveAllTestStopHandler == null) return false;
                        Log.Trace().Message("调用试验全部结束处理事件").Write();
                        OnReceiveAllTestStopHandler.Invoke(this, new TestInfoArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Info = JsonConvert.DeserializeObject<TestInfo>(sd.Value) });
                        break;

                    case "121":
                        //参数设置
                        if (OnReceiveParamDataHandler == null) return false;
                        Log.Trace().Message("调用试验参数设置处理事件，并反混淆数据").Write();
                        db = JsonConvert.DeserializeObject<DataBar>(sd.Value);
                        OnReceiveParamDataHandler?.Invoke(this, new DataArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Datas = db });
                        break;

                    case "131":
                        //实时数据
                        if (OnReceiveRealtimeDataHandler == null) return false;
                        db = JsonConvert.DeserializeObject<DataBar>(sd.Value);
                        Log.Trace().Message("调用试验实时数据处理事件，并反混淆数据").Write();
                        OnReceiveRealtimeDataHandler?.Invoke(this, new DataArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Datas = db });
                        break;

                    case "141":
                        //结果
                        if (OnReceiveResultsDataHandler == null) return false;
                        db = JsonConvert.DeserializeObject<DataBar>(sd.Value);
                        Log.Trace().Message("调用试验结果处理事件，并反混淆数据").Write();
                        OnReceiveResultsDataHandler?.Invoke(this, new DataArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Datas = db });
                        break;

                    case "160":
                        //试验状态
                        if (OnReceiveTestStatusHandler == null) return false;
                        Log.Trace().Message("调用试验状态处理事件").Write();
                        OnReceiveTestStatusHandler.Invoke(this, new StatusArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Status = JsonConvert.DeserializeObject<TestStatus>(sd.Value) });
                        break;

                    case "409":
                        //获取控制权限
                        if (OnReceiveIsControlHandler == null) return false;
                        Log.Trace().Message("调用设备控制权限处理事件").Write();
                        OnReceiveIsControlHandler.Invoke(this, new BaseArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime });
                        break;

                    default:
                        if (OnReceiveCustomHandler == null) return false;
                        Log.Trace().Message("调用自定义处理事件").Write();
                        OnReceiveCustomHandler.Invoke(this, new CustomArgs { MsgCode = sd.ActionCode, ReviceTime = sd.ActionTime, Value = sd.Value });
                        break;
                }

                return true;
            }
            catch (Exception e)
            {

                Log.Error().Exception(e).Write();
                Log.Error().Message(sd.Value).Write();
                return true;
            }
        }

        public bool InitCommand(string ip)
        {
            try
            {
                _ip = ip;
                _query = new SocketClient(_ip, 10001);
                _query.Connect();
                _data = new SocketClient(_ip, 10002);
                _readBuffer = new byte[10240];
                _lastConnect = DateTime.Now;
                _connected = true;
                return true;
            }
            catch (Exception ex)
            {
                Log.Fatal().Message(ex.Message).Write();
                return false;
            }
        }

        public void ClearEvents()
        {
            Log.Debug().Message("清理所有注册的消息事件");
            var dels = OnReceiveRealtimeDataHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理实时数据消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的实时数据消息事件");
                    OnReceiveRealtimeDataHandler -= d as EventHandler<DataArgs>;
                }
            }

            dels = OnReceiveResultsDataHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理结果消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的结果消息事件");
                    OnReceiveResultsDataHandler -= d as EventHandler<DataArgs>;
                }
            }

            dels = OnReceiveParamDataHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理参数消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的参数消息事件");
                    OnReceiveParamDataHandler -= d as EventHandler<DataArgs>;
                }
            }

            dels = OnReceiveAllTestStartHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理试验全部开始消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的试验全部开始消息事件");
                    OnReceiveAllTestStartHandler -= d as EventHandler<TestInfoArgs>;
                }
            }

            dels = OnReceiveAllTestStopHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理试验全部结束消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的试验全部结束消息事件");
                    OnReceiveAllTestStopHandler -= d as EventHandler<TestInfoArgs>;
                }
            }

            dels = OnReceiveTestStartHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理试验开始消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的试验开始消息事件");
                    OnReceiveTestStartHandler -= d as EventHandler<TestInfoArgs>;
                }
            }

            dels = OnReceiveTestStopHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理试验停止消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的试验停止消息事件");
                    OnReceiveTestStopHandler -= d as EventHandler<TestInfoArgs>;
                }
            }

            dels = OnReceiveTestAlarmHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理报警消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的报警消息事件");
                    OnReceiveTestAlarmHandler -= d as EventHandler<AlarmArgs>;
                }
            }

            dels = OnReceiveCustomHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理自定义消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的自定义消息事件");
                    OnReceiveCustomHandler -= d as EventHandler<CustomArgs>;
                }
            }

            dels = OnReceiveIsControlHandler?.GetInvocationList();
            if (dels != null)
            {
                Log.Debug().Message("清理设备控制权限消息事件");
                foreach (Delegate d in dels)
                {
                    Log.Debug().Message($"清理 {d.GetType().FullName} 的设备控制权限消息事件");
                    OnReceiveIsControlHandler -= d as EventHandler<BaseArgs>;
                }
            }
        }

        public void StartHeart()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Connect(_ip, 10003);
            _socket.BeginReceive(_readBuffer, 0, _readBuffer.Length, SocketFlags.None, _receiveHeartBeat, _socket);
            _lastConnect = DateTime.Now;

            //启动监视
            Task.Run(() => _listenConnect());

            //发送心跳
            Task.Run(() => _sendHeart());
        }

        public void StopHeart()
        {
            _connected = false;
            if (_socket != null)
            {
                _socket.Disconnect(true);
                _socket?.Dispose();
                _socket = null;
            }
        }

        public void SetMixSeed(string seed)
        {
            _seed = seed;
            QueryConnection?.SetMixSeed(seed);
            DataConnection?.SetMixSeed(seed);
        }

        public void CloseConnection()
        {
            _query.Close();
            _data.Close();
            StopHeart();
        }

        public bool Test()
        {
            var sc = new SocketClient(_ip, 10001);
            var r = sc.Connect();
            sc.Close();
            if (r) _connected = true;
            return r;
        }

        public async Task<string> Init(string language)
        {
            var sd = new SocketData
            {
                ActionCode = "000",
                Value = language
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd.Value;
        }

        public bool TestConnection(string ip)
        {
            if (string.IsNullOrEmpty(ip)) ip = _ip;
            var sc = new SocketClient(ip, 10001);
            var r = sc.Connect();
            sc.Close();
            if (r) _connected = true;
            return r;
        }

        /// <summary>
        /// 添加参数方案
        /// </summary>
        /// <param name="ps"></param>
        /// <returns>0（成功）,-1(失败),-2（方案名称已存在）</returns>
        public async Task<SocketData> AddParamSchemeAsync(ParamScheme ps)
        {
            var sd = new SocketData
            {
                ActionCode = "903",
                Value = JsonConvert.SerializeObject(ps, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto
                })
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 更新参数方案
        /// </summary>
        /// <param name="ps"></param>
        /// <returns></returns>
        public async Task<SocketData> UpdateParamSchemeAsync(ParamScheme ps)
        {
            var sd = new SocketData
            {
                ActionCode = "904",
                Value = JsonConvert.SerializeObject(ps, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto
                })
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 根据试验类型获取参数方案
        /// </summary>
        public async Task<SocketData> GetParamSchemes(int testType)
        {
            var sd = new SocketData
            {
                ActionCode = "901",
                Value = testType.ToString()
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetParamSchemeByIdAsync(int id)
        {
            var sd = new SocketData
            {
                ActionCode = "902",
                Value = id.ToString()
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetParamSchemesAsync(QueryScheme query)
        {
            var sd = new SocketData
            {
                ActionCode = "907",
                Value = JsonConvert.SerializeObject(query)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetDefaultParamSchemeAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "908",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 根据Id删除参数方案
        /// </summary>
        public async Task<SocketData> DeleteParamSchemeById(int id)
        {
            var sd = new SocketData
            {
                ActionCode = "905",
                Value = id.ToString()
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> SetDefaultSchemeAsync(int id)
        {
            var sd = new SocketData
            {
                ActionCode = "906",
                Value = id.ToString()
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetFlowConfigAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "925",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> SetFlowConfigAsync(List<IniData> datas)
        {
            var sd = new SocketData
            {
                ActionCode = "926",
                Value = JsonConvert.SerializeObject(datas)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取设备升级包的版本
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetUpdateVerForInstrumentAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "010",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd.Value;
        }

        /// <summary>
        /// 获取主程序升级包的版本
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetUpdateVerForUniversalHostAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "011",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd.Value;
        }

        /// <summary>
        /// 获取设备升级包
        /// </summary>
        /// <param name="ver"></param>
        /// <returns></returns>
        public async Task<string> GetUpdateForInstrument(string ver)
        {
            var sd = new SocketData
            {
                ActionCode = "012",
                Value = ver
            };

            return await _query.GetFileAsync(sd);
        }

        public async Task<string> RemoveUpdateForInstrumentAsync(string ver)
        {
            var sd = new SocketData
            {
                ActionCode = "014",
                Value = ver
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd.Value;
        }



        /// <summary>
        /// 获取主程序升级包
        /// </summary>
        /// <param name="ver"></param>
        /// <returns></returns>
        public string GetUpdateForUniversalHost(string ver)
        {
            var sd = new SocketData
            {
                ActionCode = "013",
                Value = ver
            };

            return _query.GetFile(sd);
        }

        public async Task<string> RemoveUpdateForUniversalHost(string ver)
        {
            var sd = new SocketData
            {
                ActionCode = "015",
                Value = ver
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd.Value;
        }

        public async Task<SocketData> GetCurrentUnitAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "016",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<string> GetCurrentDbTemplateAsync(string unit)
        {
            var sd = new SocketData
            {
                ActionCode = "017",
                Value = unit
            };

            return await _query.GetFileAsync(sd);
        }

        public async Task<SocketData> SendCustomDataAsync(string msgCode, string datas = "")
        {
            var sd = new SocketData
            {
                ActionCode = msgCode,
                Value = datas
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> SendCustomDataWithoutResponseAsync(string msgCode, string datas = "")
        {
            var sd = new SocketData
            {
                ActionCode = msgCode,
                Value = datas,
                HasResponse = false
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public SocketData SendCustomData(string msgCode, string datas = "")
        {
            var sd = new SocketData
            {
                ActionCode = msgCode,
                Value = datas
            };

            var r = _query.SendReceive(sd);
            return r.sd;
        }

        /// <summary>
        /// 101 试验开始
        /// </summary>
        public async Task<SocketData> StartTestAsync(string datas = "")
        {
            var sd = new SocketData
            {
                ActionCode = "101",
                Value = datas
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 102 手动停止单次并列试验或停止回位
        /// </summary>
        /// <param name="stopReturning">是否也停止回位</param>
        /// <returns></returns>
        public async Task<SocketData> StopSingleTestAsync(bool stopReturning)
        {
            var sd = new SocketData
            {
                ActionCode = "102",
                Value = stopReturning.ToString()
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置试验参数
        /// </summary>
        public async Task<SocketData> SetTestParams(List<FullData> paramlist)
        {
            var sd = new SocketData
            {
                ActionCode = "103",
                Value = JsonConvert.SerializeObject(paramlist)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 104 停止整个试验
        /// </summary>
        /// <param name="needSave">是否需要保存</param>
        /// <returns></returns>
        public async Task<SocketData> EndTestAsync(bool needSave)
        {
            var sd = new SocketData
            {
                ActionCode = "104",
                Value = needSave.ToString()
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 多腔试验可单开单关的设备停止单个腔的试验
        /// </summary>
        /// <param name="data">腔号</param>
        /// <returns></returns>
        public async Task<SocketData> EndTestAsync(string data)
        {
            var sd = new SocketData
            {
                ActionCode = "105",
                Value = data
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetCacheCountAsync(LostDataIndex index)
        {
            var sd = new SocketData
            {
                ActionCode = "151",
                Value = JsonConvert.SerializeObject(index)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取电子签名信息
        /// </summary>
        public async Task<SocketData> GetSignatureInfoAsync(QuerySign qs)
        {
            var sd = new SocketData
            {
                ActionCode = "211",
                Value = JsonConvert.SerializeObject(qs)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 添加电子签名信息
        /// </summary>
        public async Task<SocketData> AddSignatureInfoAsync(Esignal qs)
        {
            var sd = new SocketData
            {
                ActionCode = "212",
                Value = JsonConvert.SerializeObject(qs)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 修改电子签名信息
        /// </summary>
        public async Task<SocketData> ModifySignatureInfoAsync(Esignal qs)
        {
            var sd = new SocketData
            {
                ActionCode = "213",
                Value = JsonConvert.SerializeObject(qs)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 删除电子签名信息
        /// </summary>
        public async Task<SocketData> DeleteSignatureInfoAsync(Esignal qs)
        {
            var sd = new SocketData
            {
                ActionCode = "214",
                Value = JsonConvert.SerializeObject(qs)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }


        /// <summary>
        /// 登录验证
        /// </summary>
        public async Task<SocketData> Login(User user)
        {
            var sd = new SocketData
            {
                ActionCode = "401",
                Value = JsonConvert.SerializeObject(user)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 改密码
        /// </summary>
        public async Task<SocketData> ChangePassword(User user)
        {
            var sd = new SocketData
            {
                ActionCode = "403",
                Value = JsonConvert.SerializeObject(user)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }


        /// <summary>
        /// 用户退出
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool Logout(User user)
        {
            var sd = new SocketData
            {
                ActionCode = "404",
                Value = user.LoginName,
                HasResponse = false,
            };

            var r = _query.SendCommand(sd);
            return r.isSuccess;
        }

        /// <summary>
        /// 根据id获取用户具有的操作权限
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<SocketData> GetPermissionsByUserIdAsync(int uid)
        {
            var sd = new SocketData
            {
                ActionCode = "405",
                Value = uid + ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        public async Task<SocketData> AddUserAsync(UserInfo user)
        {
            var sd = new SocketData
            {
                ActionCode = "413",
                Value = JsonConvert.SerializeObject(user)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取用户列表（异步）
        /// </summary>
        public async Task<SocketData> GetUsersAsync(QueryUser qu)
        {
            var sd = new SocketData
            {
                ActionCode = "411",
                Value = JsonConvert.SerializeObject(qu)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取用户信息（异步）
        /// </summary>
        public async Task<SocketData> GetUserInfoAsync(QueryUser qu)
        {
            var sd = new SocketData
            {
                ActionCode = "412",
                Value = JsonConvert.SerializeObject(qu)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 修改用户信息（异步）
        /// </summary>
        public async Task<SocketData> ModifyUserAsync(UserInfo ui)
        {
            var sd = new SocketData
            {
                ActionCode = "414",
                Value = JsonConvert.SerializeObject(ui)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 删除用户（异步）
        /// </summary>
        public async Task<SocketData> DeleteUserAsync(string loginName)
        {
            var sd = new SocketData
            {
                ActionCode = "415",
                Value = loginName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 恢复用户（异步）
        /// </summary>
        public async Task<SocketData> RenewUserAsync(string loginName)
        {
            var sd = new SocketData
            {
                ActionCode = "419",
                Value = loginName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 锁定用户（异步）
        /// </summary>
        public async Task<SocketData> LockUserAsync(string loginName)
        {
            var sd = new SocketData
            {
                ActionCode = "416",
                Value = loginName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> LockUserAutoAsync(UserInfo ui)
        {
            var sd = new SocketData
            {
                ActionCode = "402",
                Value = JsonConvert.SerializeObject(ui)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 解锁用户（异步）
        /// </summary>
        public async Task<SocketData> UnlockUserAsync(string loginName)
        {
            var sd = new SocketData
            {
                ActionCode = "417",
                Value = loginName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 重置用户密码（异步）
        /// </summary>
        public async Task<SocketData> ResetPasswordAsync(string loginName)
        {
            var sd = new SocketData
            {
                ActionCode = "418",
                Value = loginName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 异步获取操作日志
        /// </summary>
        public async Task<SocketData> GetOperateLogAsync(QueryLog ql)
        {
            var sd = new SocketData
            {
                ActionCode = "501",
                Value = JsonConvert.SerializeObject(ql)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取设备运行日志
        /// </summary>
        /// <returns></returns>
        public async Task<(string result, string file)> GetRunnningLogFromPcAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "510",
                Value = ""
            };

            var filePath = await _query.GetFileAsync(sd);
            if (string.IsNullOrEmpty(filePath) || filePath.StartsWith("--"))
            {
                return (filePath?.Replace("--", "") ?? string.Empty, string.Empty);
            }

            return (string.Empty, filePath);
        }

        /// <summary>
        /// 角色名是否存在(异步)
        /// </summary>
        public async Task<SocketData> CheckRoleNameAsync(string name)
        {
            var sd = new SocketData
            {
                ActionCode = "420",
                Value = name
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取全部角色信息(异步)
        /// </summary>
        public async Task<SocketData> GetRolesAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "421",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 添加角色(异步)
        /// </summary>
        public async Task<SocketData> AddRoleAsync(RoleInfoSimple ris)
        {
            var sd = new SocketData
            {
                ActionCode = "423",
                Value = JsonConvert.SerializeObject(ris)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 修改角色(异步)
        /// </summary>
        public async Task<SocketData> UpdateRoleAsync(RoleInfoSimple ris)
        {
            var sd = new SocketData
            {
                ActionCode = "424",
                Value = JsonConvert.SerializeObject(ris)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 删除角色(异步)
        /// </summary>
        public async Task<SocketData> DeleteRoleAsync(int roleId)
        {
            var sd = new SocketData
            {
                ActionCode = "425",
                Value = roleId.ToString()
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取角色信息(异步)
        /// </summary>
        public async Task<SocketData> GetRoleInfoAsync(int roleid)
        {
            var sd = new SocketData
            {
                ActionCode = "426",
                Value = JsonConvert.SerializeObject(roleid)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取全部权限信息(异步)
        /// </summary>
        public async Task<SocketData> GetPermissionsAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "427",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取所有报警信息
        /// 只有管理员和设备控制上位机可以获取
        /// </summary>
        /// <returns></returns>
        public SocketData GetAlarms()
        {
            var sd = new SocketData
            {
                ActionCode = "-01",
                Value = ""
            };

            var r = _query.SendReceive(sd);
            return r.sd;
        }

        public async Task<SocketData> GetAlarmPlugsAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "-05",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }



        /// <summary>
        /// 删除报警信息
        /// </summary>
        /// <param name="alarm"></param>
        /// <returns></returns>
        public async Task<SocketData> ProcessAlarms(Alarm alarm)
        {
            var sd = new SocketData
            {
                ActionCode = "-02",
                Value = JsonConvert.SerializeObject(alarm),
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> ProcessAlarmsByCode(Alarm alarm)
        {
            var sd = new SocketData
            {
                ActionCode = "-06",
                Value = JsonConvert.SerializeObject(alarm)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        #region 标定&量程

        /// <summary>
        /// 获取所有传感器
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetSensorsAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "911",
                Value = ""
            };
            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取当前量程下的所有标定记录
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetCaliRecordsAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "912",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取当前量程下的标定记录信息
        /// </summary>
        /// <param name="recordName"></param>
        /// <returns></returns>
        public async Task<SocketData> GetCaliRecordAsync(string recordName)
        {
            var sd = new SocketData
            {
                ActionCode = "913",
                Value = recordName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 更新标定记录
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        public async Task<SocketData> UpdateCaliRecordAsync(LineCaliRecord record)
        {
            var sd = new SocketData
            {
                ActionCode = "914",
                Value = JsonConvert.SerializeObject(record)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 删除标定记录
        /// </summary>
        /// <param name="recordName"></param>
        /// <returns></returns>
        public async Task<SocketData> DeleteCaliRecordAsync(string recordName)
        {
            var sd = new SocketData
            {
                ActionCode = "915",
                Value = recordName
            };
            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置默认标定记录
        /// </summary>
        /// <param name="recordName"></param>
        /// <returns></returns>
        public async Task<SocketData> SetDefaultCaliRecordAsync(string recordName)
        {
            var sd = new SocketData
            {
                ActionCode = "916",
                Value = recordName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取传感器的Ad和值
        /// </summary>
        /// <param name="sensor"></param>
        /// <returns></returns>
        public async Task<SocketData> GetAdAndValueAsync(Sensor sensor)
        {
            var sd = new SocketData
            {
                ActionCode = "917",
                Value = JsonConvert.SerializeObject(sensor)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 标定传感器
        /// </summary>
        /// <param name="cali"></param>
        /// <returns></returns>
        public async Task<SocketData> CaliSensorAsync(LineCali cali)
        {
            var sd = new SocketData
            {
                ActionCode = "918",
                Value = JsonConvert.SerializeObject(cali)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取所有支持多量程的传感器
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetSensorRangesAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "920",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取所有量程
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetRangesAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "921",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 更新量程
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        public async Task<SocketData> UpdateRangeAsync(Range range)
        {
            var sd = new SocketData
            {
                ActionCode = "922",
                Value = JsonConvert.SerializeObject(range)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 删除量程
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        public async Task<SocketData> DeleteRangeAsync(Range range)
        {
            var sd = new SocketData
            {
                ActionCode = "923",
                Value = JsonConvert.SerializeObject(range)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 改变传感器量程
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        public async Task<SocketData> ChangeRangeForSensorAsync(SensorRange range)
        {
            var sd = new SocketData
            {
                ActionCode = "924",
                Value = JsonConvert.SerializeObject(range)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }
        #endregion

        #region 设置

        /// <summary>
        /// 获取设备的时间
        /// </summary>
        /// <returns></returns>
        public SocketData GetRemoteTime()
        {
            var sd = new SocketData
            {
                ActionCode = "317",
                Value = ""
            };

            var r = _query.SendReceive(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置设备时间
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> SetRemoteTimeAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "318",
                Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取设备Ip地址
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetRemoteIpAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "311",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> SetRemoteIpAsync(Ip ip)
        {
            var sd = new SocketData
            {
                ActionCode = "312",
                Value = JsonConvert.SerializeObject(ip)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取基本信息
        /// </summary>
        public async Task<SocketData> GetBaseInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "003",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 检测升级信息
        /// </summary>
        public async Task<SocketData> CheckUpdateAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "004",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }
        public SocketData GetBaseInfo()
        {
            var sd = new SocketData
            {
                ActionCode = "003",
                Value = ""
            };

            var r = _query.SendReceive(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置基本信息(异步)
        /// </summary>
        public async Task<SocketData> SetBaseInfoAsync(BaseInfo bi)
        {
            var sd = new SocketData
            {
                ActionCode = "302",
                Value = JsonConvert.SerializeObject(bi)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取安全信息(异步)
        /// </summary>
        public async Task<SocketData> GetSafeInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "309",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置安全信息(异步)
        /// </summary>
        public async Task<SocketData> SetSafeInfoAsync(SafeInfo si)
        {
            var sd = new SocketData
            {
                ActionCode = "310",
                Value = JsonConvert.SerializeObject(si)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取磁盘信息(异步)
        /// </summary>
        public async Task<SocketData> GetDiskInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "305",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置磁盘信息(异步)
        /// </summary>
        public async Task<SocketData> SetDiskInfoAsync(DiskInfo di)
        {
            var sd = new SocketData
            {
                ActionCode = "306",
                Value = JsonConvert.SerializeObject(di)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取数据盾配置(异步)
        /// </summary>
        public async Task<SocketData> GetDsInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "303",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> DataShieldTestAsync(string connectStr)
        {
            var sd = new SocketData
            {
                ActionCode = "319",
                Value = connectStr
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置数据盾配置(异步)
        /// </summary>
        public async Task<SocketData> SetDsInfoAsync(DataShieldInfo dsi)
        {
            var sd = new SocketData
            {
                ActionCode = "304",
                Value = JsonConvert.SerializeObject(dsi)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取GMP信息(异步)
        /// </summary>
        public async Task<SocketData> GetGmpInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "307",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置GMP信息(异步)
        /// </summary>
        public async Task<SocketData> SetGmpInfoAsync(GmpInfo gi)
        {
            var sd = new SocketData
            {
                ActionCode = "308",
                Value = JsonConvert.SerializeObject(gi)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取单位体系列表(异步)
        /// </summary>
        public async Task<SocketData> GetUnitSysInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "313",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 添加单位体系(异步)
        /// </summary>
        public async Task<SocketData> AddUnitSysAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "314",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<string> AddUnitSysAsync(string file)
        {
            var str = await _query.SendFileAsync(new SocketData { ActionCode = "314", Value = file });
            return str;
        }

        /// <summary>
        /// 删除单位体系(异步)
        /// </summary>
        public async Task<SocketData> DeleteUnitSysAsync(Units units)
        {
            var sd = new SocketData
            {
                ActionCode = "315",
                Value = JsonConvert.SerializeObject(units)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置默认单位体系(异步)
        /// </summary>
        public async Task<SocketData> SetDefaultUnitSysAsync(Units units)
        {
            var sd = new SocketData
            {
                ActionCode = "316",
                Value = JsonConvert.SerializeObject(units)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetTempAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "320",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetTempCtrlFunAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "328",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取温控信息(异步)
        /// </summary>
        public async Task<SocketData> GetTempCtrlInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "321",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取参数值(异步)
        /// </summary>
        public async Task<SocketData> GetTempParamValueAsync(TpctParam tpi)
        {
            var sd = new SocketData
            {
                ActionCode = "322",
                Value = JsonConvert.SerializeObject(tpi)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置参数值(异步)
        /// </summary>
        public async Task<SocketData> SetTempParamValueAsync(TpctParam tpi)
        {
            var sd = new SocketData
            {
                ActionCode = "323",
                Value = JsonConvert.SerializeObject(tpi)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 设置温控相关控制项状态(异步)
        /// </summary>
        public async Task<SocketData> SetTempControlledItemStatusAsync(ParamValue tcii)
        {
            var sd = new SocketData
            {
                ActionCode = "324",
                Value = JsonConvert.SerializeObject(tcii)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }


        public async Task<string> GetDefaultUnitZipAsync(string unit)
        {
            var sd = new SocketData
            {
                ActionCode = "326",
                Value = unit
            };

            return await _query.GetFileAsync(sd);
        }

        public string GetDefaultUnitZip(string unit)
        {
            var sd = new SocketData
            {
                ActionCode = "326",
                Value = unit
            };

            return _query.GetFile(sd);
        }

        public async Task<SocketData> GetRealtimeTempAsync(int umc)
        {
            var sd = new SocketData
            {
                ActionCode = "327",
                Value = umc + ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetTracedParamsAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "330",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetParamsForTraceAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "331",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> InsertOneParamForTraceAsync(ParamForTrace pft)
        {
            var sd = new SocketData
            {
                ActionCode = "332",
                Value = JsonConvert.SerializeObject(pft)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> RemoveOneParamForTraceAsync(ParamForTrace pft)
        {
            var sd = new SocketData
            {
                ActionCode = "333",
                Value = JsonConvert.SerializeObject(pft)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetRemoteHostAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "334",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> TestRemoteHostAsync(RemoteInfo ri)
        {
            var sd = new SocketData
            {
                ActionCode = "335",
                Value = JsonConvert.SerializeObject(ri)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> SetRemoteHostAsync(RemoteInfo ri)
        {
            var sd = new SocketData
            {
                ActionCode = "336",
                Value = JsonConvert.SerializeObject(ri)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetReportConfigsAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "341",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> UpdateReportConfigAsync(ReportConfig cfg)
        {
            var sd = new SocketData
            {
                ActionCode = "342",
                Value = JsonConvert.SerializeObject(cfg)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取自定义信息
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetCustomInfoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "351",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 更新自定义信息
        /// </summary>
        /// <param name="ci"></param>
        /// <returns></returns>
        public async Task<SocketData> UpdateCustomInfoAsync(CustomInfo ci)
        {
            var sd = new SocketData
            {
                ActionCode = "352",
                Value = JsonConvert.SerializeObject(ci)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 发送自定义Logo文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> SendCustomLogoAsync(string file)
        {
            var str = await _query.SendFileAsync(new SocketData { ActionCode = "353", Value = file }, false);
            return str;
        }

        /// <summary>
        /// 发送自定义缩略图文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> SendCustomThumbAsync(string file)
        {
            var str = await _query.SendFileAsync(new SocketData { ActionCode = "354", Value = file }, false);
            return str;
        }

        /// <summary>
        /// 获取自定义logo文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<(string result, string file)> GetCustomLogoAsync(string file)
        {
            var sd = new SocketData
            {
                ActionCode = "355",
                Value = file
            };

            var filePath = await _query.GetFileAsync(sd);
            if (string.IsNullOrEmpty(filePath) || filePath.StartsWith("--"))
            {
                return (filePath?.Replace("--", "") ?? string.Empty, string.Empty);
            }
            return (string.Empty, filePath);
        }

        /// <summary>
        /// 获取自定义缩略图文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<(string result, string file)> GetCustomThumbAsync(string file)
        {
            var sd = new SocketData
            {
                ActionCode = "356",
                Value = file
            };

            var filePath = await _query.GetFileAsync(sd);
            if (string.IsNullOrEmpty(filePath) || filePath.StartsWith("--"))
            {
                return (filePath?.Replace("--", "") ?? string.Empty, string.Empty);
            }
            return (string.Empty, filePath);
        }
        #endregion

        #region 备份还原
        /// <summary>
        /// 获取设备上的U盘
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetUDiskAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "440",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 从设备端备份数据库
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> BackupDatabaseFromDeviceAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "444",
                Value = string.Empty
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 从PC端备份数据库
        /// </summary>
        /// <returns></returns>
        public async Task<(string result, string file)> BackupDatabaseFromPcAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "444",
                Value = "true"
            };

            var filePath = await _query.GetFileAsync(sd);
            if (string.IsNullOrEmpty(filePath) || filePath.StartsWith("--"))
            {
                return (filePath?.Replace("--", string.Empty) ?? "", string.Empty);
            }

            return (string.Empty, filePath);
        }

        /// <summary>
        /// 从设备端还原数据库
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> RestoreDatabaseFromDeviceAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "445",
                Value = string.Empty
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> GetBackupAutoAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "446",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> SetBackupAutoAsync(AutoBackupConfig cfg)
        {
            var sd = new SocketData
            {
                ActionCode = "447",
                Value = JsonConvert.SerializeObject(cfg)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetDataManageRecordAsync(QueryBase query)
        {
            var sd = new SocketData
            {
                ActionCode = "448",
                Value = JsonConvert.SerializeObject(query)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> UpdateBackupAsync(DataManageRecord record)
        {
            var sd = new SocketData
            {
                ActionCode = "449",
                Value = JsonConvert.SerializeObject(record)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 从PC端还原数据库
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> RestoreDatabaseFromPcAsync(string file)
        {
            var str = await _query.SendFileAsync(new SocketData { ActionCode = "445", Value = file });
            return str;
        }

        /// <summary>
        /// 从设备端备份试验数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<SocketData> BackupTestDataFromDeviceAsync(QueryBackup query)
        {
            query.IsLocal = true;
            var sd = new SocketData
            {
                ActionCode = "441",
                Value = JsonConvert.SerializeObject(query)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 从PC端备份试验数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<(string result, string file)> BackupTestDataFromPcAsync(QueryBackup query)
        {
            query.IsLocal = false;
            var sd = new SocketData
            {
                ActionCode = "441",
                Value = JsonConvert.SerializeObject(query)
            };

            var filePath = await _query.GetFileAsync(sd);
            if (string.IsNullOrEmpty(filePath) || filePath.StartsWith("--"))
            {
                return (filePath?.Replace("--", "") ?? string.Empty, string.Empty);
            }
            return (string.Empty, filePath);
        }



        /// <summary>
        /// 从设备端导出试验数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<SocketData> ExportTestDataFromDeviceAsync(QueryBackup query)
        {
            query.IsLocal = true;
            var sd = new SocketData
            {
                ActionCode = "442",
                Value = JsonConvert.SerializeObject(query)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 从PC端导出试验数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<(string result, string file)> ExportTestDataFromPcAsync(QueryBackup query)
        {
            query.IsLocal = false;
            var sd = new SocketData
            {
                ActionCode = "442",
                Value = JsonConvert.SerializeObject(query)
            };

            var filePath = await _query.GetFileAsync(sd);
            if (string.IsNullOrEmpty(filePath) || filePath.StartsWith("--"))
            {
                return (filePath?.Replace("--", "") ?? string.Empty, string.Empty);
            }
            return (string.Empty, filePath);
        }

        /// <summary>
        /// 从设备端还原试验数据
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> RestoreTestDataFromDeviceAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "443",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }
        /// <summary>
        /// 从PC端还原实验数据
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> RestoreTestDataFromPcAsync(string file)
        {
            var str = await _query.SendFileAsync(new SocketData { ActionCode = "443", Value = file });
            return str;
        }
        #endregion

        /// <summary>
        /// 添加一条操作日志
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public async Task<SocketData> AddOpLogAsync(OperateLog log)
        {
            var sd = new SocketData
            {
                ActionCode = "502",
                Value = JsonConvert.SerializeObject(log)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        #region 试验查询
        /// <summary>
        /// 获取试验记录
        /// </summary>
        /// <param name="qd"></param>
        /// <returns></returns>
        public async Task<SocketData> GetTestDataAsync(QueryData qd)
        {
            var sd = new SocketData
            {
                ActionCode = "201",
                Value = JsonConvert.SerializeObject(qd)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 获取试验文件
        /// </summary>
        /// <param name="files">试验文件全路径</param>
        /// <returns>试验文件压缩包路径</returns>
        public string GetTestDataFiles(List<string> files)
        {
            var sd = new SocketData
            {
                ActionCode = "206",
                Value = JsonConvert.SerializeObject(files)
            };

            return _query.GetFile(sd);
        }

        public string GetTestDataFile(int testid)
        {
            var sd = new SocketData
            {
                ActionCode = "208",
                Value = testid + ""
            };

            return _query.GetFile(sd);
        }

        public async Task<SocketData> SendToDataShieldAsync(List<string> files)
        {
            var sd = new SocketData
            {
                ActionCode = "224",
                Value = JsonConvert.SerializeObject(files)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetSendRecordsAsync(QueryBase qb)
        {
            var sd = new SocketData
            {
                ActionCode = "225",
                Value = JsonConvert.SerializeObject(qb)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> DeleteSendRecordAsync(string fileName)
        {
            var sd = new SocketData
            {
                ActionCode = "226",
                Value = fileName
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> DeleteSendRecordsAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "227",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> DeleteTestDatasAsync(List<int> ids)
        {
            var sd = new SocketData
            {
                ActionCode = "204",
                Value = JsonConvert.SerializeObject(ids)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetTagAndRemarkAsync(int testId)
        {
            var sd = new SocketData
            {
                ActionCode = "207",
                Value = testId + ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> GetSelfQuerysAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "209",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        public async Task<SocketData> UpdateTagAndRemarkAsync(TagAndRemark tr)
        {
            var sd = new SocketData
            {
                ActionCode = "205",
                Value = JsonConvert.SerializeObject(tr)
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }
        #endregion

        /// <summary>
        /// 重启设备软件
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> DeviceResetAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "090",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }

        /// <summary>
        /// 初始化设备
        /// </summary>
        /// <returns></returns>
        public async Task<SocketData> DeviceInitAsync()
        {
            var sd = new SocketData
            {
                ActionCode = "091",
                Value = ""
            };

            var r = await _query.SendReceiveAsync(sd);
            return r.sd;
        }
    }
}
